// watermark.js
Page({
  data: {
    imageUrl: '',
    resultImageUrl: '',
    watermarkType: 'text', // 'text' or 'image'
    watermarkText: '水印文字',
    fontSize: 36,
    textColor: '#FFFFFF',
    watermarkImageUrl: '',
    watermarkSize: 20,
    opacity: 80,
    position: 'bottom-right',
    processing: false
  },

  onLoad() {
    console.log('水印页面加载');
  },

  chooseImage() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        this.setData({
          imageUrl: res.tempFiles[0].tempFilePath,
          resultImageUrl: ''
        });
      },
      fail: (err) => {
        console.error('选择图片失败:', err);
        wx.showToast({
          title: '选择图片失败',
          icon: 'error'
        });
      }
    });
  },

  chooseWatermarkImage() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        this.setData({
          watermarkImageUrl: res.tempFiles[0].tempFilePath
        });
      },
      fail: (err) => {
        console.error('选择水印图片失败:', err);
        wx.showToast({
          title: '选择水印图片失败',
          icon: 'error'
        });
      }
    });
  },

  switchWatermarkType(e) {
    this.setData({
      watermarkType: e.currentTarget.dataset.type
    });
  },

  onTextInput(e) {
    this.setData({
      watermarkText: e.detail.value
    });
  },

  onFontSizeChange(e) {
    this.setData({
      fontSize: e.detail.value
    });
  },

  selectTextColor(e) {
    this.setData({
      textColor: e.currentTarget.dataset.color
    });
  },

  onWatermarkSizeChange(e) {
    this.setData({
      watermarkSize: e.detail.value
    });
  },

  onOpacityChange(e) {
    this.setData({
      opacity: e.detail.value
    });
  },

  selectPosition(e) {
    this.setData({
      position: e.currentTarget.dataset.position
    });
  },

  addWatermark() {
    if (!this.data.imageUrl) {
      wx.showToast({
        title: '请先选择图片',
        icon: 'error'
      });
      return;
    }

    if (this.data.watermarkType === 'text' && !this.data.watermarkText.trim()) {
      wx.showToast({
        title: '请输入水印文字',
        icon: 'error'
      });
      return;
    }

    if (this.data.watermarkType === 'image' && !this.data.watermarkImageUrl) {
      wx.showToast({
        title: '请选择水印图片',
        icon: 'error'
      });
      return;
    }

    this.setData({ processing: true });

    wx.getImageInfo({
      src: this.data.imageUrl,
      success: (res) => {
        const { width, height } = res;
        
        // 直接使用旧版canvas以确保兼容性
        this.addWatermarkLegacy(width, height);
      },
      fail: (err) => {
        console.error('获取图片信息失败:', err);
        this.setData({ processing: false });
        wx.showToast({
          title: '获取图片信息失败',
          icon: 'error'
        });
      }
    });
  },

  // 降级到旧版canvas的方法
  addWatermarkLegacy(width, height) {
    // 设置canvas尺寸
    this.setData({
      canvasWidth: width,
      canvasHeight: height
    });
    
    // 延时确保canvas尺寸更新
    setTimeout(() => {
      const canvas = wx.createCanvasContext('watermarkCanvas', this);
      
      // 绘制原图
      canvas.drawImage(this.data.imageUrl, 0, 0, width, height);
      
      // 设置透明度
      canvas.setGlobalAlpha(this.data.opacity / 100);
      
      if (this.data.watermarkType === 'text') {
        this.drawTextWatermark(canvas, width, height);
      } else {
        this.drawImageWatermark(canvas, width, height);
      }
    }, 50); // 延时50ms确保canvas尺寸更新
  },

  drawTextWatermark(canvas, width, height) {
    // 设置文字样式
    canvas.setFontSize(this.data.fontSize);
    canvas.setFillStyle(this.data.textColor);
    canvas.setTextAlign('left');
    canvas.setTextBaseline('top');
    
    // 计算文字位置
    const textMetrics = canvas.measureText(this.data.watermarkText);
    const textWidth = textMetrics.width;
    const textHeight = this.data.fontSize;
    
    const position = this.calculatePosition(width, height, textWidth, textHeight);
    
    // 绘制文字
    canvas.fillText(this.data.watermarkText, position.x, position.y);
    
    this.finishWatermark(canvas, width, height);
  },

  drawImageWatermark(canvas, width, height) {
    wx.getImageInfo({
      src: this.data.watermarkImageUrl,
      success: (watermarkInfo) => {
        const watermarkWidth = width * (this.data.watermarkSize / 100);
        const watermarkHeight = (watermarkInfo.height / watermarkInfo.width) * watermarkWidth;
        
        const position = this.calculatePosition(width, height, watermarkWidth, watermarkHeight);
        
        canvas.drawImage(
          this.data.watermarkImageUrl,
          position.x,
          position.y,
          watermarkWidth,
          watermarkHeight
        );
        
        this.finishWatermark(canvas, width, height);
      },
      fail: (err) => {
        console.error('获取水印图片信息失败:', err);
        this.setData({ processing: false });
        wx.showToast({
          title: '获取水印图片信息失败',
          icon: 'error'
        });
      }
    });
  },

  calculatePosition(canvasWidth, canvasHeight, watermarkWidth, watermarkHeight) {
    const padding = 20;
    let x, y;
    
    switch (this.data.position) {
      case 'top-left':
        x = padding;
        y = padding;
        break;
      case 'top-center':
        x = (canvasWidth - watermarkWidth) / 2;
        y = padding;
        break;
      case 'top-right':
        x = canvasWidth - watermarkWidth - padding;
        y = padding;
        break;
      case 'center-left':
        x = padding;
        y = (canvasHeight - watermarkHeight) / 2;
        break;
      case 'center':
        x = (canvasWidth - watermarkWidth) / 2;
        y = (canvasHeight - watermarkHeight) / 2;
        break;
      case 'center-right':
        x = canvasWidth - watermarkWidth - padding;
        y = (canvasHeight - watermarkHeight) / 2;
        break;
      case 'bottom-left':
        x = padding;
        y = canvasHeight - watermarkHeight - padding;
        break;
      case 'bottom-center':
        x = (canvasWidth - watermarkWidth) / 2;
        y = canvasHeight - watermarkHeight - padding;
        break;
      case 'bottom-right':
      default:
        x = canvasWidth - watermarkWidth - padding;
        y = canvasHeight - watermarkHeight - padding;
        break;
    }
    
    return { x, y };
  },

  // 新版2D canvas文字水印绘制
  drawTextWatermark2D(ctx, width, height, canvas) {
    // 设置文字样式
    ctx.font = `${this.data.fontSize}px sans-serif`;
    ctx.fillStyle = this.data.textColor;
    ctx.textAlign = 'left';
    ctx.textBaseline = 'top';
    
    // 计算文字位置
    const textMetrics = ctx.measureText(this.data.watermarkText);
    const textWidth = textMetrics.width;
    const textHeight = this.data.fontSize;
    
    const position = this.calculatePosition(width, height, textWidth, textHeight);
    
    // 绘制文字
    ctx.fillText(this.data.watermarkText, position.x, position.y);
    
    this.finishWatermark2D(canvas);
  },

  // 新版2D canvas图片水印绘制
  drawImageWatermark2D(ctx, width, height, canvas) {
    const watermarkImg = canvas.createImage();
    watermarkImg.onload = () => {
      const watermarkWidth = width * (this.data.watermarkSize / 100);
      const watermarkHeight = (watermarkImg.height / watermarkImg.width) * watermarkWidth;
      
      const position = this.calculatePosition(width, height, watermarkWidth, watermarkHeight);
      
      ctx.drawImage(
        watermarkImg,
        position.x,
        position.y,
        watermarkWidth,
        watermarkHeight
      );
      
      this.finishWatermark2D(canvas);
    };
    watermarkImg.onerror = () => {
      this.setData({ processing: false });
      wx.showToast({
        title: '水印图片加载失败',
        icon: 'error'
      });
    };
    watermarkImg.src = this.data.watermarkImageUrl;
  },

  // 新版2D canvas完成水印
  finishWatermark2D(canvas) {
    wx.canvasToTempFilePath({
      canvas: canvas,
      success: (res) => {
        this.setData({
          resultImageUrl: res.tempFilePath,
          processing: false
        });
        
        wx.showToast({
          title: '水印添加完成',
          icon: 'success'
        });
      },
      fail: (err) => {
        console.error('生成水印图片失败:', err);
        this.setData({ processing: false });
        wx.showToast({
          title: '生成水印图片失败',
          icon: 'error'
        });
      }
    });
  },

  // 旧版canvas完成水印
  finishWatermark(canvas, width, height) {
    canvas.draw(false, () => {
      setTimeout(() => {
        wx.canvasToTempFilePath({
          canvasId: 'watermarkCanvas',
          success: (res) => {
            this.setData({
              resultImageUrl: res.tempFilePath,
              processing: false
            });
            
            wx.showToast({
              title: '水印添加完成',
              icon: 'success'
            });
          },
          fail: (err) => {
            console.error('生成水印图片失败:', err);
            this.setData({ processing: false });
            wx.showToast({
              title: '生成水印图片失败',
              icon: 'error'
            });
          }
        });
      }, 100); // 延时确保绘制完成
    });
  },

  saveImage() {
    if (!this.data.resultImageUrl) {
      wx.showToast({
        title: '没有可保存的图片',
        icon: 'error'
      });
      return;
    }

    wx.saveImageToPhotosAlbum({
      filePath: this.data.resultImageUrl,
      success: () => {
        wx.showToast({
          title: '保存成功',
          icon: 'success'
        });
      },
      fail: (err) => {
        if (err.errMsg.includes('auth deny')) {
          wx.showModal({
            title: '提示',
            content: '需要授权访问相册才能保存图片',
            success: (res) => {
              if (res.confirm) {
                wx.openSetting();
              }
            }
          });
        } else {
          wx.showToast({
            title: '保存失败',
            icon: 'error'
          });
        }
      }
    });
  },

  resetImage() {
    this.setData({
      imageUrl: '',
      resultImageUrl: '',
      watermarkImageUrl: ''
    });
  }
})